package repository;

import java.io.File;
import java.io.IOException;

import fileoperation.FileCreation;

public class Repository {
    private static String workTree;	//working directory
    private static String gitDir;	//jit repository path

    /**
     * Constructor
     */
    public Repository() throws IOException {
        if(gitDir == ""){
            throw new IOException("The repository does not exist!");
        }
    }
    
    /**
     * Construct a new repository instance with certain path.
     * Constructor
     * @param path
     * @throws IOException
     */
    public Repository(String path) throws IOException {
        this.workTree = path;
        this.gitDir = path + File.separator + ".jit";
    }

    public static String getGitDir() {
        return gitDir;
    }

    public static String getWorkTree() {
        return workTree;
    }
    
    /**
     * Helper functions.
     * @return
     */
    public boolean exist(){ return new File(gitDir).exists(); }

    public boolean isFile(){ return new File(gitDir).isFile(); }

    public boolean isDirectory(){ return new File(gitDir).isDirectory(); }


    /**
     * Create the repository and files and directories inside.
     * @return boolean
     * @throws IOException
     */
    public void createRepo() throws IOException {
        // 创建 .jit 文件夹
        FileCreation.createDirectory(workTree, ".jit");

        /* 创建初始化文件\文件夹 */
        // objects/info
        // objects/pack
        FileCreation.createDirectory(gitDir, new String[]{"objects", "info"});
        FileCreation.createDirectory(gitDir, new String[]{"objects", "pack"});
        // refs/heads
        // refs/tags
        FileCreation.createDirectory(gitDir, new String[]{"refs", "heads"});
        FileCreation.createDirectory(gitDir, new String[]{"refs", "tags"});
        // logs
        FileCreation.createDirectory(gitDir, "logs");
        // hooks
        FileCreation.createDirectory(gitDir, "hooks");
        // branches
        FileCreation.createDirectory(gitDir, "branches");
        // HEAD
        FileCreation.createFile(gitDir, "HEAD", "ref: refs"+File.separator+"heads"+File.separator+"master\n");
        // index
        FileCreation.createFile(gitDir, "index", "");
        // config
        FileCreation.createFile(gitDir, "config",
                "[core]\n" +
                     "\trepositoryformatversion = 0\n" +
                     "\tfilemode = false\n" +
                     "\tbare = false\n" +
                     "\tlogallrefupdates = true\n" +
                     "\tsymlinks = false\n" +
                     "\tignorecase = true\n");
        // description
        FileCreation.createFile(gitDir, "description",
                "Unnamed repository; edit this file 'description' to name the repository.\\n");
    }

}
